package com.tanhua.commons.huanxin.utils;


import com.alibaba.fastjson.JSON;
import com.tanhua.commons.huanxin.config.HuanXinConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;


@Component
public class TokenUtils {

    @Autowired
    private HuanXinConfig huanXinConfig;

    @Autowired
    private RestTemplate restTemplate;

    private String token;

    private long expire = 0L;

    public String getToken() {
        Long now = System.currentTimeMillis();
        if(now > expire) {
            String url = this.huanXinConfig.getUrl()
                    + this.huanXinConfig.getOrgName() + "/"
                    + this.huanXinConfig.getAppName() + "/token";

            Map<String, Object> param = new HashMap<>();

            param.put("grant_type", "client_credentials");
            param.put("client_id", this.huanXinConfig.getClientId());
            param.put("client_secret", this.huanXinConfig.getClientSecret());

            ResponseEntity<String> responseEntity = this.restTemplate.postForEntity(url, param, String.class);

            if (responseEntity.getStatusCodeValue() != 200) {
                return null;
            }

            String body = responseEntity.getBody();

            Map<String,String> map1 = JSON.parseObject(body, Map.class);

            token = map1.get("access_token");
            expire = System.currentTimeMillis() + 24 * 60 * 60 * 1000;
        }
        return token;
    }
}
